<?php

namespace app\common\model;

use app\helpers\Common;
use app\libs\traits\BaseModelTrait;

use think\facade\Cache;

class Region extends Base
{
    /**
     * Base Model Trait
     */
    use BaseModelTrait;

    // 当前模型名称 不带前缀
    protected $name = 'regions';

    // 主键
    protected $pk = 'id';


    /**
     * 获取树状结构
     *
     * @param bool $isUpdate 是否更新
     */
    public static function getTreeDatas($isUpdate = false)
    {
        $cacheKey = 'cache-tree_region';
        if ($isUpdate) {
            Cache::delete($cacheKey);
        }
        $list = Cache::get($cacheKey);
        if (!$list) {
            $where = [
                ['level', '<', 3]
            ];
            $list = self::where($where)->select()->toArray();
            if ($list) {
                // 处理列表数据
                $list = list_to_tree($list, 'area_code', 'parent_code', 'children', 0);
            }
            Cache::set($cacheKey, $list, 3600 * 24 * 30);
        }

        return $list;
    }
}